using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace Netduino4Fun.Framework.ElectronicBrick
{
    public class PulseButton
    {
        InterruptPort input;
        long previousInteruptTicks;

        public PulseButton(Cpu.Pin pin)
        {
            this.input = new InterruptPort(pin, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
            previousInteruptTicks = DateTime.Now.Ticks;
            this.input.OnInterrupt += new NativeEventHandler(port_OnInterrupt);                    
        }

        void port_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            long delta = time.Ticks - previousInteruptTicks;
            previousInteruptTicks = time.Ticks;

            bool pushed = data2 == 1;
            if (pushed)
            {
                if (PulseStart != null)
                    PulseStart(this, new PulseEventArgs { Delta = delta });
            }
            else
            {
                if (PulseEnd != null)
                    PulseEnd(this, new PulseEventArgs { Delta = delta });
            }
        }

        public delegate void PulseEventHandler(object sender, PulseEventArgs e);

        public event PulseEventHandler PulseStart;
        public event PulseEventHandler PulseEnd;
    }

    public class PulseEventArgs : EventArgs
    {
        public double Delta { get; set; }
    }
}
